//app.js
var util = require('/util/util.js');
const qiniuUploader = require("/util/qiniuUploader");
App({
  data:{
    
   //'apiHost': 'http://tenement.com/',
    'apiHost': 'https://www.bestsmartbee.com/',
    'mockUrl':'http://www.apidoc.com/mock2?uri=',
    'qiniuUrl':'http://oi7jj3s01.bkt.clouddn.com/',
    'websocket': 'wss://www.boxphp.me',
    //'websocket': 'ws://127.0.0.1:9501',
    'mock': 0,//全局使用mock请求 
    debug:1,
    wxapp:"",
    socketOpen:false,
    socketMsgQueue:[],
    socketRevQueue:{},
    getUserInfoCb:[],
  },
  pageData:{},
  util: util,
  window:function(){
     //console.log("window");
     var _this=this;
      wx.getSystemInfo({complete:function(res){
          _this.globalData.window=res;
          _this.globalData.window.rpx=750/res.windowWidth;
      }})
  },
  getShopInfo(){
    var extConfigSync = this.getExtConfigSync();
    var shop_info = wx.getStorageSync("shop_info");
    if (!shop_info) {
      shop_info = extConfigSync.shop_list[0];
      wx.getStorageSync("shop_info", shop_info);
    }
    return shop_info;
  },
  getLocation:function(cb){
    var that = this
    if (this.globalData.userLocation) {
      typeof cb == "function" && cb(this.globalData.userLocation)
    } else {
      wx.getLocation({
        type: 'gcj02', //返回可以用于wx.openLocation的经纬度
        success: function (res) {
          //  console.log(res);
            that.globalData.userLocation = res;
            typeof cb == "function" && cb(that.globalData.userLocation);
        }
      })
    }
  },
  //
  runGetUserInfoCb:function(userInfo){
    for (var i in this.data.getUserInfoCb){
      var fun = this.data.getUserInfoCb[i];
      typeof fun == "function" && fun(userInfo);
    }
    this.data.getUserInfoCb=[];
  },

  loginByUserInfo: function (userInfo, cb) {
    // console.log(userInfo);
    var that = this;
    //调用登录接口
    wx.login({
      fail: function (res) {
        console.log(res);
      },
      success: function (loginRes) {
        // console.log("loginRes", loginRes);
        var pid = wx.getStorageSync("pid");
        if (pid>0){
          userInfo.pid = pid;
          wx.removeStorageSync("pid");
        }
        
        userInfo.method = "POST";
        userInfo.code = loginRes.code;
        userInfo.wxapp = that.data.wxapp;
        userInfo.fields = "user_id,store_id,phone,nickname,phone,avatarUrl,last_update_time,partner_user_id";
        userInfo.rawData = JSON.stringify(userInfo.userInfo);
        that.api("/api/user/loginByWxApp", userInfo, function (userRes) {
          console.log("userRes", userRes);
          if (userRes.code == 3 || !userRes.data.phone) {
            wx.navigateTo({
              url: '/pages/user/bindphone?page=bindphone',
            })
            return false;
          }
          if (userRes.code != 200 && userRes.code != 3) {
            that.alert(userRes.msg);
            return false;
          }
          // console.log(userRes);
          that.globalData.userInfo = userRes.data
          that.runGetUserInfoCb(that.globalData.userInfo);
          typeof cb == "function" ? cb(userRes) : '';
        });
      }
    })
  },
  GetRequest: function (url) {
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
      var str = url.split("?");
      str = str[1];
      var strs = str.split("&");
      for (var i = 0; i < strs.length; i++) {
        var v = strs[i].split("=")[1];
        theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
      }
    }
    return theRequest;
  },
  getUserInfo: function (cb) {
   // console.log(this.data.getUserInfoCb.length);
    var that = this
    this.data.getUserInfoCb.push(cb);
    if (this.data.getUserInfoCb.length > 1) {
      return;
    }
    var user_info = this.globalData.userInfo;
    console.log(user_info);
    if (user_info) {
      this.runGetUserInfoCb(user_info);
      //typeof cb == "function" && cb(this.globalData.userInfo)
    } else {
      console.log("getSetting");
      wx.getSetting({
        complete: function (res){
          if (res.errMsg !="getSetting:ok"){
            that.alert(res.errMsg);
          }
          console.log("getSetting complete", res);
        },
        success: function (res) {
          console.log("getSetting success");
          console.log(res);
          console.log(res.authSetting['scope.userInfo']);
          if (res.authSetting['scope.userInfo']) {
            // 已经授权，可以直接调用 getUserInfo 获取头像昵称
            wx.getUserInfo({
              success: function (res) {
                console.log(res);
                that.loginByUserInfo(res);
              },
              fail: function (res) {
                that.alert('授权失败!');
              },
              complete: function (res) {
                console.log("getUserInfo complete", res);
              }
            })

          } else if (!res.authSetting['scope.userInfo']) {
            console.log("redirectTo ", "/pages/user/bindphone?page=auth");
           // that.alert("/pages/user/bindphone?page=auth");
            wx.reLaunch({
              url: '/pages/user/bindphone?page=auth',
              complete:function(res){
                console.log(res);
              }
            })
          }
        }
      })

    }
  },
  globalData:{
    userInfo:null,
    window:{}
  },
  onShow: function() {
    console.log("onshow");
    var that = this;
    // wx.onUserCaptureScreen(function (res) {
    //   that.alert("用户截屏了");
    // })
      // Do something when show.
    this.autoUpdate();
  },

  autoUpdate: function () {
    console.log(new Date())
    var self = this
    // 获取小程序更新机制兼容
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      //1. 检查小程序是否有新版本发布
      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          //2. 小程序有新版本，则静默下载新版本，做好更新准备
          updateManager.onUpdateReady(function () {
            console.log(new Date())
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function (res) {
                if (res.confirm) {
                  //3. 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  updateManager.applyUpdate()
                } else if (res.cancel) {
                  //如果需要强制更新，则给出二次弹窗，如果不需要，则这里的代码都可以删掉了
                  wx.showModal({
                    title: '温馨提示~',
                    content: '本次版本更新涉及到新的功能添加，旧版本无法正常访问的哦~',
                    success: function (res) {
                      self.autoUpdate()
                      return;
                      //第二次提示后，强制更新
                      if (res.confirm) {
                        // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                        updateManager.applyUpdate()
                      } else if (res.cancel) {
                        //重新回到版本更新提示
                        self.autoUpdate()
                      }
                    }
                  })
                }
              }
            })
          })
          updateManager.onUpdateFailed(function () {
            // 新的版本下载失败
            wx.showModal({
              title: '已经有新版本了哟~',
              content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
            })
          })
        }
      })
    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },

  onHide: function() {
     console.log("onHide");
      // Do something when hide.
  },
  getExtConfigSync:function(){
    let extConfig = wx.getExtConfigSync ? wx.getExtConfigSync() : {}
    if (!extConfig.theme){
      extConfig.theme ="pages_black";
    }
    return extConfig;
  },
  getUrl:function(url,data){

    var params = this.requestParam(url, data);
    var json = params.param;
    var arg = Object.keys(json).map(function (key) {
      return encodeURIComponent(key) + "=" + encodeURIComponent(json[key]);
    }).join("&");
    var hash = "wechat_redirect";

    if (params.url.indexOf("#") > -1) {
      var urls = params.url.split("#");
      url = urls[0];
      hash = urls[1];
    } else {
      url = params.url;
    }

    if (url.indexOf("?") > -1) {
      url = url + "&" + arg;
    } else {
      url = url + "?" + arg;
    }
    return url + "#" + hash;

   
  },
  //请求接口
 requestParam:function(url,data,cb){
   var host=this.data.apiHost; 
   if (url.indexOf("http")!==0){
      url = host + url;
   }
   var param={};
   var cbf=cb;
   if(typeof(data)=='function'){
     cbf=data; 
   }else if(typeof(data)=='object'){
    param=data;
   }
   this.data.debug == 1 ? param['time'] = Date.parse(new Date()) :'';

  
  //  console.log("extConfig", extConfig);
   param['from_wx_app']=1;
   if (param['store_id']==-1){
     delete param['store_id'];
   }else{
     param['store_id'] = 1;
   }
   
   param['appid'] = "wx1687899545e698ae";

   
   //param['uuid']='wx101';
   var user_info = this.globalData.userInfo && this.globalData.userInfo.token ? this.globalData.userInfo : wx.getStorageSync("user_info");

   param['token'] = user_info ? user_info.token:'';
   param['runThreadKey']='eee50acd6ee441d75ad2b87c9747d09b'; 
   console.log("param:", param);
   return {
     'param':param,
     'url':url,
     'cb':cbf,
   };
 },

 

 api:function(url,data={},cb){
  //  console.log("api",data);
   if (url.indexOf("http") === 0) {
     var apiUrl = url;
   } else {
     var apiUrl = this.data.apiHost + url;
   }
   //console.log(this.data.mock);
   if (data['mock']==1 || this.data.mock ==1){
     apiUrl = this.data.mockUrl+url;
   }
   if (data['mock'] == 0 ){
     apiUrl = this.data.apiHost+url;
   }

   this.postData(apiUrl,data,cb);
 },

 postData:function(url,data,cb){
  //  wx.showToast({
  //    title: '加载中...',
  //    icon: 'loading',
  //    duration: 5000
  //  });
   wx.showNavigationBarLoading();
   var p=this.requestParam(url,data,cb);
   console.log("postData:", p);
   var method = p['param']['method'] ? p['param']['method'] :'GET';
  // console.log("postData:");
   var cbf = p['cb'];
  // 数据缓存
   if (p['param']['cacheKey']){
      var cacheData = wx.getStorageSync(p['param']['cacheKey']);
     if (cacheData){
       console.log("cacheKey:", p['param']['cacheKey'], cacheData);
       typeof (cbf) == "function" ? cbf(cacheData) : "";
       wx.hideNavigationBarLoading();
       return;
     }
   }
  
  
   wx.request({
        url: p['url'], //仅为示例，并非真实的接口地址
        data: p['param'],
        method: method,
        // header: {
        //    'Content-Type': 'application/json'
        // },
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },  
        success: function(res) {
          typeof(cbf)=="function"?cbf(res.data):"";
         // wx.hideToast();
         
          if (p['param']['cacheKey'] && (res.data.code == 200 || res.data.success)) {
                wx.setStorage({
                  key: p['param']['cacheKey'],
                  data: res.data
                })
           }
          wx.hideNavigationBarLoading();
        }
    })
 },
 //页面的数据 
  //页面的数据 
  setPageData: function (pageName, data = {}) {
    var curData = this.pageData[pageName] ? this.pageData[pageName] : {};
    // console.log("setPageData",data);
    for (var i in data) {
      //console.log("i", i, data[i]);
      curData[i] = data[i];
    }

    this.pageData[pageName] = curData;
    console.log(this.pageData);
  },
  getPageData: function (pageName, key = '') {
    var curData = this.pageData[pageName];
    if (key) {
      return curData ? curData[key] : null;
    } else {
      return curData;
    }
  },
  //上传图片
 upload: function (filePath, suc) {
   var that = this;
   wx.showToast({
     title: '上传中...',
     icon: 'loading',
     duration: 5000
   });
   qiniuUploader.upload(filePath, (res) => {
     // that.setData({
     //   'imageURL': res.imageURL,
     // });
     wx.hideToast();
     suc ? suc(res) : '';
   }, (error) => {
     console.log('error: ' + error);
     that.alert(JSON.stringify(error));
   }, {
       region: 'ECN', // 华东区
       uploadURL: 'https://up.qiniup.com',
       domain: this.data.qiniuUrl,
       uptokenURL: this.data.apiHost+'/api/upload/uptoken',
     })

 },
  alert:function(content){
    wx.showModal({
      title: '提示',
      content: content,
      showCancel:false,
    })
  },
   onLaunch: function (options) {
     //建connectSocket
   //  this.connectSocket();
     //console.log(options);
    // Do something initial when launch.
    var that = this;
     this.window();
     
     this.getUserInfo(function (userInfo) {
       console.log(userInfo);
       wx.setStorageSync("user_info", userInfo);
      // that.getNoti()//用户消息提醒
     });
    
  },
  //提醒小红点
   setRedDot:function(){
     if (wx.showTabBarRedDot) {
       wx.showTabBarRedDot({
         index: 3,
       });
     }else{
      //  wx.setNavigationBarTitle({
      //    title: '您有未读消息...'
      //  });
       //this.alert("您有未读消息,请到我的用户中心查看");
      
     }
   },
   clearRedDot: function () {
     if (wx.hideTabBarRedDot) {
        wx.hideTabBarRedDot({
          index: 3,
        });
     }else{

     }
   },
   
   getNoti:function(){
     var that = this;
     this.api("api/user/info", {}, function (res) {
       if (res.code != 200) {
         app.alert(res.msg);
         return;
       }
       if (res.data.allNoti>0){
         that.setRedDot();
       }
     })   
     
   },
   sendSocketMessage:function(data){
     var data = JSON.stringify(data);
     console.log("send:",data);
     if (this.data.socketOpen === false) {
       this.data.socketMsgQueue.push(data);
     }else{
       wx.sendSocketMessage({
         data: data
       });
     }
   },

  revMessage(k,fn){
    this.data.socketRevQueue[k] = fn;
  },
   
  //connectSocket
   connectSocket:function(data){
     var that =this;
     wx.connectSocket({
       url: this.data.websocket
     });
     wx.onSocketOpen(function (res) {
       console.log('onSocketOpen');
       that.data.socketOpen = true
       console.log(that.data.socketMsgQueue);
       for (var i = 0; i < that.data.socketMsgQueue.length; i++) {
         wx.sendSocketMessage({
           data: that.data.socketMsgQueue[i]
         });
       }
       that.data.socketMsgQueue = []
     })

     wx.onSocketMessage(function (r) {
       var res = JSON.parse (r.data);
       var key = res.dosometing;
       //判断页面是否打开中,聊天页面没有打开，那么消息提醒 
       var chatShow = that.getPageData("user/chat", 'show');
       if (key == "chatMessage" && chatShow==0){
         that.api("message/incMessagesCount",{
           f_user_id: res.user.user_id
         });
         return ;
       }
       //执行dosometing
       if (key && that.data.socketRevQueue[key] && typeof (that.data.socketRevQueue[key])=="function"){
         that.data.socketRevQueue[key](res);
       }
      
      // console.log('收到服务器内容：', res);
     })
     var that = this;
     wx.onSocketError(function (res) {

      // that.alert('WebSocket连接打开失败，请检查！');
       console.log(res)
     })
     wx.onSocketClose(function (res) {
       console.log('WebSocket 已关闭！')
     })
   },
   thumb_up:function(topic_id,suc,fail){//点赞
   var that = this;
     this.api('sns/topic/thumb_up', {
       topic_id: topic_id,
       method: 'POST',
     }, function (res) {
       if (res.code != 200) {
         fail ? fail(res):'';
         that.alert(res.msg);
         return;
       }
       suc ? suc(res.data):'';
     });
   },
   in_array: function (search, array) {
     for (var i in array) {
       if (array[i] == search) {
         return i;
       }
     } 
     return false;
   },
   DateDiff(sDate1, sDate2) {    //sDate1和sDate2是2006-12-18格式    
     var day1 = new Date(sDate1);
     var day2 = new Date(sDate2);
     return Math.floor((day2 - day1) / (1000 * 60 * 60 * 24));
     //   return  iDays + 1
   },
   date(i=0){
     var now = new Date();
     now.setDate(now.getDate() + i);
     var m = Number(now.getMonth()) + 1;
     var d = Number(now.getDate());
     if (m < 10) {
       m = "0" + m;
     }
     if (d < 10) {
       d = "0" + d;
     }
     return now.getFullYear() + "-" + m + "-" + d;
   },
   
})